package com.xdclass.mobile.mobilexdclassredis.service;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.xdclass.mobile.mobilexdclassredis.domain.SysUser;
import com.xdclass.mobile.mobilexdclassredis.domain.SysUserExample;
import com.xdclass.mobile.mobilexdclassredis.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * Created whit IntelliJ IDEA
 * User:杨骏杰
 * Date:2021/3/30
 * Time:12:26
 * guava布隆过滤器
 */
@Service
public class BloomFilterService {

    @Resource
    private SysUserMapper sysUserMapper;

    private BloomFilter<Integer> bloomFilter;

    /**
     * PostConstruct 程序启动的时候加载此方法
     */
    @PostConstruct
    public void initBloomFilter(){
        SysUserExample sysUserExample = new SysUserExample();
        List<SysUser> sysUsersList = sysUserMapper.selectByExample(sysUserExample);
        //判断sysUsersList是否为空
        if(CollectionUtils.isEmpty(sysUsersList)){
            return;
        }
        //创建布隆过滤器，使用int类型(默认误码率为3%)
        bloomFilter = BloomFilter.create(Funnels.integerFunnel(),sysUsersList.size());
        for (SysUser sysUser : sysUsersList){
            //在布隆过滤器中注入id
            bloomFilter.put(sysUser.getId());
        }


    }

    /**
     * 判断id可能存在于布隆过滤器里面
     * @param id
     * @return
     */
    public boolean userIdExists(int id){
        return bloomFilter.mightContain(id);
    }
}
